﻿;(function(){
	// @private
    function toggleButtons(smObj){
        if(smObj.hasSelection()){
            $$.every(this, function(action){
                action.enable();
            });
        }else{
            $$.every(this, function(action){
                action.disable();
            });
        }
    }
    
    // @private
    function onRowContextMenu(grid, rowNum, event){
        event.preventDefault();
        if(!grid.getSelectionModel().hasSelection()){
            grid.getSelectionModel().selectRow(rowNum);
        }
        this.showAt(event.getXY()); // this是一个Edit Menu
    }
    
    // @private
    function createSelectAllBtn(){
        var selectAll_Btn = new Ext.menu.Item({
             textTpl : '全选这{0}笔记录'
            ,handler : createSelectAllBtn.bbar_SelectAll_Handler
            ,scope   : this
        });
        
        this.store.on('load', createSelectAllBtn.updateRecordSum, selectAll_Btn);
        
        this.bbar_SelectAll = selectAll_Btn;
        
        return selectAll_Btn;
    }

    createSelectAllBtn.bbar_SelectAll_Handler = function(){
        // selectionAll_Record_OnSession
        this.getSelectionModel().selectAll();
        var feedbackStr = '你已经' + this.bbar_SelectAll.text + '。即使后面未显示的记录都均以选择！';
        /*
        blogService.setState(0, function(){
            Ext.feedback.msg(Edk.config.appStr, feedbackStr);
        });
        */
    }
    createSelectAllBtn.updateRecordSum = function(storeObj){
        this.setText(this.textTpl.format(storeObj.getTotalCount()));
    }
    
    // @paivate
    // 默认的动作，这里所有的成语都会传入Ext.Action的构造器  
    var defaultActions = {
        create: {
             text       : '新建'
            ,iconCls    : 'icon16-create'
            ,tooltip    : '<b>新建记录(Create)</b><br />对数据库新增加的INSERT指令。'
            ,handler    : function(btn){
                var container = btn.ownerCt.ownerCt.ownerCt; 
                container.add(
                	new $$.formPanel({
                		 title:"（未保存）"
                        ,loadUpdateFn : blogService.editPost
                        ,loadCreateFn : blogService.loadCreate
                        ,data         : {
                        	State : 'create'
                        }
                	}
                ));
            },itemId: 'create'
                
        }
        ,read: {
             text       : '打开'
            ,disabled   : true
            ,iconCls    : 'icon16-read'
            ,tooltip    : '<b>打开记录(Read)</b><br />使用SELECT指令搜索数据库表示其结果来读取数据。'
            ,handler    : function(btn, event, container){
                if(!this.hasSelection()){
                    $$.Action.noSelected();
                    return false;
                }
                $$.every(this.getSelections(), function(itemObj){
                    var id = itemObj.id;
                    var viewPanel = new Ext.Panel({
                         id        : "viewPanel_" + id
                        ,title     : itemObj.data['title']
                        ,closable  : true
                        ,autoScroll: true
                    });
                    viewPanel.recordId = id;
                    
                    this.add(viewPanel);
                    
                    blogService.viewPost({ ID : id }, viewPanel.body.update, viewPanel.body);
                    
                }, container || btn.ownerCt.ownerCt.ownerCt);							
            }       	
        }		
        ,update: {
             text       : '编辑'
            ,iconCls    : 'icon16-update'
            ,disabled   : true
            ,tooltip    : '<b>编辑</b><br />数据的更新(update)对应UPDATE指令。'
            ,handler    : function(btn, event, container){
                if(!this.hasSelection()){
                    $$.Action.noSelected();
                    return false;
                }
                $$.every(this.getSelections(), function(itemObj){
                	// how to get blogService?
                    var updatePnl = new $$.formPanel({
                         id           : "editingPanel_" + itemObj.id
                        ,loadUpdateFn : blogService.editPost
                        ,loadCreateFn : blogService.loadCreate
                        ,data         : {
                        	 ID    : itemObj.id
                        	,State : 'update'
                        }
                    });
                    this.add(updatePnl);	
                }, container || btn.ownerCt.ownerCt.ownerCt);
            }         	
        }
        ,del: {
             text       : '删除'
            ,iconCls    : 'icon16-delete'
            ,disabled   : true
            ,tooltip    : '<b>删除记录</b><br />数据的删除分别对应1行删除的DELETE指令。'
            ,handler    : function(ui){
                var 
                     smObj    = this[0]
                    ,callback = this[1], scope = this[2]
                    ,showMsg  = function(){
                        Ext.feedback.msg(Edk.config.tips,'“{0}”共{1}项删除完毕。'.format(textStr.substr(0, 20), i));
                    }
                   ,callback = (callback && typeof(callback) == 'function')
                                ?showMsg.createSequence(callback, scope)
                                :showMsg
                    ,msg     = 
                        "您确<b>删除</b>以下{0}条记录？<br/>" +
                        "-----------------------------------<br/>" +
                        "<ol class=\"showListDecimal\"><li>{1}</li></ol>"
                    ,selection, textStr, idNum, i;
                
                if(smObj.hasSelection()){
                    selection = smObj.getSelections();
                    if(!(selection[0].data)['ID']){
                    	// @todo
	                    Edk.Suite.Action.noSelected();
	                    return false;                   	
                    }
                }else{
                    Edk.Suite.Action.noSelected();
                    return false;
                }
                if (selection.length == 1) {
                    textStr = (selection[0].data)['title'];
                    idNum   = (selection[0].data)['ID'];
                    i = 1;
                }else {
                    textStr = [], idNum = [];
                    for (i = 0; i < selection.length; i++) {
                        textStr.push((selection[i].data)['title']);
                        idNum.push((selection[i].data)['ID']);
                    }
                    textStr = textStr.join('</li><li>');
                }
				
                Ext.Msg.show({
                     title       : document.title
                    ,msg         : msg.format(i, textStr)
                    ,width       : 340
                    ,buttons     : Ext.MessageBox.YESNO
                    ,icon        : Ext.MessageBox.QUESTION
                    ,multiline   : false
                    ,animEl      : ui.getEl()
                    ,fn          : function(btn){
                        if (btn != "yes") 
                            return false;
                        blogService.del(idNum.pop ? idNum : [ idNum ], callback, scope);
                    }
                });	            
            }     	
        }  
    };
    
    // @private
    var defaultColumns = [
         {
            id:'id',    header:"#id",  dataIndex:"ID", align:'center', sortable: true, 
            renderer: function(v, meta){
                meta.css = 'Edk-numberStyle_1';
                return v;
            }
         }
        ,{
             id:'title', header: "标题", sortable: false,  menuDisabled:true, dataIndex: 'title'
            ,renderer: function(value, metaData, record, x, y, store){
                var str, briefStr = record.data['brief'].substr(0, 100);
                var arr = briefStr.split('');
                var insertStr;
                if(arr.length > 70){
                    insertStr = arr[Math.round(arr.length/2)];
                    arr[Math.round(arr.length/2)] = (insertStr += '<br />');
                    briefStr = arr.join('');
                }
                str = (store.showBrief === true)
                    ?'<b>{0}</b><p style="color:gray;margin-bottom:3px;">{1}</p>'.format(value, briefStr)
                    :value;
                return str;
            }
        }
        ,{
              id:'catalog', header: "分类", sortable: true, align:'center', menuDisabled:true, dataIndex: 'catalogTitle'
             ,renderer: {
                fn: function(value, metaData, record){
                    var 
                         gridId  = "'" + this.id + "'"
                        ,ClassID = record.json.ClassID 
                        ,tplStr  = '<a href="{0}" onClick="Ext.getCmp({1}).loadCatalog({2});">{3}</a>';
                    
                    return tplStr.format('javascript:void(0);', gridId, ClassID,  record.json.catalogTitle);
                }
            }
        }
        ,{
              id:'createDate', header: "创建日期", sortable: true, align:'center', dataIndex: 'createDate'
             ,renderer: function(v){
                return v ? Edk.JSON.decodeDate(v).format(Edk.Date.masks.shortDate2) : null;
             }
        }
    ];
    
    /**
     * @class $$.grid
     * @extends Ext.grid.GridPanel
     */
    $$.grid = Ext.extend(Ext.grid.GridPanel, {
         autoExpandColumn: 'title'
        ,loadMask       : {
        	msg: '加载中…'
        }
        ,enableDragDrop : true
	    ,stripeRows     : true
        ,closable       : true
        ,border         : false
		,title          : '数据一览表'
        ,ddGroup        : 'myDD_group'
		
		,initComponent: function(){

			this.sm      = new Ext.grid.RowSelectionModel();
		    this.columns = this.getColumn();// 设定列模型
			this.actions = this.getActions();
			this.tbar    = new Ext.Toolbar(this.getTopBar());
		    this.bbar    = new Ext.PagingToolbar(this.getBottomBar());
		    
			$$.grid.superclass.initComponent.call(this); 
			
			//“行”的右键菜单
		    this.on('rowcontextmenu', onRowContextMenu, new Ext.menu.Menu(this.getContextMenu()));
			
			// 双击行会发生什么？默认是“打开记录”
			// ----------请读者注意，注释内的d代码是重构前的代码------
			//this.on('rowdblclick', function(){actions.read.execute(null, null, this);}, this.getTabContainer());
			// ------------------------------------------------
			this.on('rowdblclick', function(){this.actions['read'].execute(null, null, this.getTabContainer());}, this);
			
			// 切换按钮是否可用的状态
			this.getSelectionModel().on('selectionchange', toggleButtons, this.getToggleButtons());
			
      		/**
             * 是否使用摘要的字段
             */
			this.store.baseParams = {
				uiType :'ext-direct-grid'
			};
            this.store.showBrief = true;
			this.store.load();
		}

		// 实例方法
		,loadCatalog: function(nsIdNum){
			var 
				 store    = this.getStore()
				,cataTree = this.catalogTreeNode;
				
			store.baseParams['ns'] = nsIdNum;
			store.load();
			// 如果Tree展开了有关分类的子节点，选中吧！
			if(cataTree && cataTree.isExpanded() && cataTree.isLoaded()){
				cataTree.findChild(nsIdNum).select();
			}
		}
		,getColumn : function(){
		    // 设定单元格渲染器的函数作用域
		    $$.every(defaultColumns, function(col){
		    	if(col.renderer){
		    		col.renderer.scope = this;
		    	}
		    }, this);
		    
            return defaultColumns;
		}
		,getActions : function(){
            var actions = {};
            var sm = this.sm;// 建立Ext.Action、分配scope(Action适宜于SelectionModel关联起来，他们的关系较为紧密)
           
            for(var i in defaultActions){
                if(i == 'del'){
                    defaultActions[i].scope = [ sm, this.store.reload, this.store ]; // 删除之后，需要刷新Store的记录
                }else{
                    defaultActions[i].scope = sm;
                }
                actions[i] = new Ext.Action(defaultActions[i]);
            }
            return actions;
		}
		,getTopBar : function(){
            var actions = this.actions;
            var defaultTopBarBtns = [ actions.create, actions.read, actions.del, actions.update ];

            return defaultTopBarBtns;
		}
		,getBottomBar: function(){
            var sm = this.sm;
            var PagingToolbarCfg = {
		         store       : this.store
		        ,pageSize    : this.gridPageSize || 8
		        ,displayInfo : true
		        ,items       : [{
		             xtype   : 'splitbutton'
		            ,text    : '全选'
		            ,handler : sm.selectAll
		            ,scope   : sm
		            ,menu    : [
						 createSelectAllBtn.call(this)
						,{
			            	 text     : '取消选择'
			            	,handler  : sm.clearSelections
			            	,scope    : sm
		            	}
		            ]
		        }]
	        };
	        return PagingToolbarCfg;
		}
		,getContextMenu : function(){
            var actions = this.actions;
            var defaultMenuItems = [ actions.read, actions.del, actions.update ];
            var menuCfg = {
			    items: defaultMenuItems
			};
			
            return menuCfg;
		}
		,getToggleButtons : function(){
            var actions = this.actions;
            var btns = [actions.read, actions.del, actions.update];
            
            return btns;
		}
	});
})();	
Ext.reg('EdkGrid', $$.grid);